package com.itheima.chapter12.reflect;

import com.itheima.chapter12.reflect.Domain.Student;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

/*
反射类中成员变量
 */
public class Demo3 {
    public static void main(String[] args) throws NoSuchFieldException, InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchMethodException {
        Class<Student> studentClass = Student.class;
        Field[] declaredFields = studentClass.getDeclaredFields();
        System.out.println(declaredFields);
        Field name = studentClass.getDeclaredField("name");
        Field age = studentClass.getDeclaredField("age");
        age.setAccessible(true);
        name.setAccessible(true);

        //根据空参构造，创建学生对象
        Constructor<Student> constructor = studentClass.getConstructor();
        Student stu1 = constructor.newInstance();
        Student stu2 = constructor.newInstance();

        //使用成员变量完成赋值
        name.set(stu1,"张三");
        age.set(stu1,23);
        name.set(stu2,"李四");
        age.set(stu2,24);
        Object o = age.get(stu1);
        System.out.println(o);
        System.out.println(name.get(stu2));
        System.out.println(stu1);
        System.out.println(stu2);
    }
}
